<!DOCTYPE html>
<html lang="en" class="light">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>2-Factor Authentication</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-start: hsla(202, 71%, 27%, 1);
            --bg-end: hsla(176, 45%, 66%, 1);
        }
        .dark {
            --bg-start: hsla(252, 40%, 29%, 1);
            --bg-end: hsla(270, 77%, 71%, 1);
        }
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(90deg, var(--bg-start), var(--bg-end));
            background-size: 400% 400%;
            animation: gradientAnimation 15s ease infinite;
        }
        @keyframes gradientAnimation {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        .bg-card {
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
        }
        .dark .bg-card { background-color: rgba(0, 0, 0, 0.2); border: 1px solid rgba(255, 255, 255, 0.15); }
        .light .bg-card { background-color: rgba(255, 255, 255, 0.2); border: 1px solid rgba(255, 255, 255, 0.25); }
        .form-input {
            border: 1px solid transparent;
            transition: all 0.2s ease-in-out;
        }
        .dark .form-input { background-color: rgba(0, 0, 0, 0.25); border-color: rgba(100, 100, 100, 0.4); }
        .light .form-input { background-color: rgba(255, 255, 255, 0.25); border-color: rgba(255, 255, 255, 0.4); }
    </style>
     <script>
        // Theme toggling logic
        function setTheme(theme) {
            document.documentElement.classList.toggle('dark', theme === 'dark');
            localStorage.setItem('theme', theme);
        }
        document.addEventListener('DOMContentLoaded', () => {
            const storedTheme = localStorage.getItem('theme');
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            setTheme(storedTheme || (prefersDark ? 'dark' : 'light'));
        });
        function toggleTheme() {
            const isDark = document.documentElement.classList.contains('dark');
            setTheme(isDark ? 'light' : 'dark');
        }
    </script>
</head>
<body class="min-h-screen flex items-center justify-center p-4 text-gray-800 dark:text-gray-100">
    <div class="bg-card shadow-2xl rounded-3xl p-8 w-full max-w-sm relative text-center">
         <button onclick="toggleTheme()" class="absolute top-4 right-4 p-2 rounded-full text-white/70 hover:text-white hover:bg-white/20 dark:hover:bg-black/20 transition-colors duration-200">
            <!-- Theme toggle SVG -->
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V3a.75.75 0 01.75-.75zM7.5 7.625A.75.75 0 018.25 7.5h.75a.75.75 0 01.75.75v.75a.75.75 0 01-.75.75h-.75A.75.75 0 017.5 8.375v-.75zM15 7.5a.75.75 0 01.75.75v.75a.75.75 0 01-1.5 0v-.75a.75.75 0 01.75-.75zM17.65 6.33a.75.75 0 011.06 0l1.06 1.06a.75.75 0 010 1.06l-1.06 1.06a.75.75 0 01-1.06 0L17.65 7.39a.75.75 0 010-1.06zM6.34 17.65a.75.75 0 010-1.06l1.06-1.06a.75.75 0 011.06 0l1.06 1.06a.75.75 0 010 1.06l-1.06 1.06a.75.75 0 01-1.06 0zM12 17.25a.75.75 0 01.75.75v2.25a.75.75 0 01-1.5 0V18a.75.75 0 01.75-.75zM2.25 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5H3a.75.75 0 01-.75-.75zM18 12a.75.75 0 01.75-.75h2.25a.75.75 0 010 1.5h-2.25a.75.75 0 01-.75-.75zM12 7.5a4.5 4.5 0 100 9 4.5 4.5 0 000-9z" /></svg>
        </button>
        <div class="mb-6">
            <div class="w-16 h-16 mx-auto bg-gradient-to-br from-indigo-500 to-purple-500 rounded-full flex items-center justify-center text-white text-3xl font-bold shadow-lg mb-4">
                🛡️
            </div>
            <h1 class="text-3xl font-semibold text-white/95">Verification Required</h1>
            <p class="text-white/70 mt-2">Enter your verification code to complete your login.</p>
        </div>

        <form id="mfa-challenge-form" class="space-y-6">
            <div>
                <label for="mfa-code" class="sr-only">Verification Code</label>
                <input id="mfa-code" name="mfa-code" type="text" required placeholder="123456 or ABC-DEF-GHI"
                       class="form-input block w-full px-5 py-3 rounded-xl text-white text-center tracking-wider text-xl">
                 <p class="text-xs text-center text-white/60 mt-2">
                    Lost your device? <a href="#" class="font-semibold text-purple-300 hover:text-purple-200">Use a recovery code.</a>
                </p>
            </div>
            <div id="message-box" class="text-center text-sm font-medium hidden"></div>
            <button type="submit" class="w-full py-3 px-4 rounded-xl font-semibold text-white text-lg bg-gradient-to-r from-cyan-500 to-teal-500 hover:from-cyan-600 hover:to-teal-600 transition-all">
                Complete Login
            </button>
        </form>
    </div>

    <script>
        function getCookie(name) {
            const nameEQ = name + "=";
            const ca = document.cookie.split(';');
            for(let i=0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
            }
            return null;
        }
        function deleteCookie(name) {
            document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        }

        const mfaForm = document.getElementById('mfa-challenge-form');
        const messageBox = document.getElementById('message-box');
        const mfaCodeInput = document.getElementById('mfa-code');

        mfaForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const button = e.target.querySelector('button[type="submit"]');
            button.disabled = true;

            const urlParams = new URLSearchParams(window.location.search);
            const mfaToken = urlParams.get('mfa_token');
            const code = mfaCodeInput.value;

            if (!mfaToken) {
                showMessage('MFA token missing from URL.', 'text-red-300/90');
                button.disabled = false;
                return;
            }

            if (!code || code.length < 6) {
                 showMessage('Please enter a valid code.', 'text-red-300/90');
                 button.disabled = false;
                 return;
            }

            try {
                const response = await fetch('/mfa/validate-login', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ mfa_token: mfaToken, code: code })
                });

                const data = await response.json();
                if (response.ok) {
                    showMessage(data.message, 'text-green-300/90');
                    const returnUrl = getCookie('return_url');
                    deleteCookie('return_url');
                    setTimeout(() => window.location.href = returnUrl || '/ui/dashboard', 2000);
                } else {
                    showMessage(data.detail || 'Verification failed.', 'text-red-300/90');
                }
            } catch (error) {
                showMessage('Network error. Please try again.', 'text-red-300/90');
            } finally {
                button.disabled = false;
            }
        });

        function showMessage(text, colorClass) {
            messageBox.textContent = text;
            messageBox.className = `text-center text-sm font-medium ${colorClass}`;
            messageBox.style.display = 'block';
        }
    </script>
</body>
</html>
